<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Client WebSocket</title>
</head>
<body>
<button id="bt">发送</button>
<input type="text" id="tx">
<div class="chat"></div>

<script>
    var bt = document.getElementById("bt");

    var clientWebSocket = new WebSocket("ws://localhost:8080/echo");
    clientWebSocket.onopen = function () {
        console.log("clientWebSocket.onopen", clientWebSocket);
        console.log("clientWebSocket.readyState", clientWebSocket.readyState);
        clientWebSocket.send("你好！");
    }
    clientWebSocket.onclose = function (error) {
        console.log("clientWebSocket.onclose", clientWebSocket, error);
        events("聊天会话关闭！");
    }

    function events(responseEvent) {
        document.querySelector(".chat").innerHTML += responseEvent + "<br>";
    }

    bt.onclick = function () {
        var tx = document.getElementById("tx").value;
        clientWebSocket.send(tx);
    }


    clientWebSocket.onmessage = function (data) {
        document.querySelector(".chat").innerHTML += data.data + "<br>";
    }

</script>
</body>
</html>